/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml;

/** The variable size integer. */
public final class VInteger {

    private static final long[] LENGTH_DESCRIPTOR = {
            0x80L,
            0x4000L,
            0x200000L,
            0x10000000L,
            0x0800000000L,
            0x040000000000L,
            0x02000000000000L,
            0x0100000000000000L,
    };

    private static final long[] VALUE_MASK = {
            0x7fL,
            0x3fffL,
            0x1fffffL,
            0x0fffffffL,
            0x07ffffffffL,
            0x03ffffffffffL,
            0x01ffffffffffffL,
            0x00ffffffffffffffL,
    };


    private final long value;

    private final long encodedValue;

    private final int encodedSize;


    /**
     * Creates a new <code>VInteger</code> object.
     *
     * @param value the value
     * @param encodedValue the value in the encoded form
     * @param encodedSize the size of the value in the encoded form
     */
    private VInteger(long value, long encodedValue, int encodedSize) {
        this.value = value;
        this.encodedValue = encodedValue;
        this.encodedSize = encodedSize;
    }


    /**
     * Creates a new <code>VInteger</code> with the specified value.
     *
     * @param value the value
     *
     * @return the new <code>VInteger</code>
     *
     * @throws IllegalArgumentException if <code>value</code> is negative or greater then
     * <code>72057594037927934L</code> (<code>0x00fffffffffffffeL</code>)
     */
    public static VInteger encode(long value) {
        if (value < 0L || value > 0x00fffffffffffffeL) {
            throw new IllegalArgumentException();
        }
        int encodedSize = 1;
        while ((value & VALUE_MASK[encodedSize - 1]) != value) {
            encodedSize++;
        }
        if ((value & VALUE_MASK[encodedSize - 1]) == VALUE_MASK[encodedSize - 1]) {
            encodedSize++;
        }
        return new VInteger(value, LENGTH_DESCRIPTOR[encodedSize - 1] | value, encodedSize);
    }

    /**
     * Creates a new <code>VInteger</code> with the specified value.
     *
     * @param value the value
     * @param encodedSize the required size of the value in the encoded form
     *
     * @return the new <code>VInteger</code>
     *
     * @throws IllegalArgumentException if <code>value</code> is negative or greater then
     * <code>72057594037927934L</code> (<code>0x00fffffffffffffeL</code>), if <code>encodedSize</code> is less then
     * <code>1</code> or greater then <code>8</code>, or if it is not possible to encode the <code>value</code> as a
     * variable size integer of the specified size
     */
    public static VInteger encode(long value, int encodedSize) {
        if (value < 0L || value > 0x00fffffffffffffeL
                || encodedSize < 1 || encodedSize > 8
                || (value & VALUE_MASK[encodedSize - 1]) != value
                || (value & VALUE_MASK[encodedSize - 1]) == VALUE_MASK[encodedSize - 1]) {
            throw new IllegalArgumentException();
        }
        return new VInteger(value, LENGTH_DESCRIPTOR[encodedSize - 1] | value, encodedSize);
    }

    /**
     * Creates a new <code>VInteger</code> with the specified value.
     *
     * @param encodedValue the value in the encoded form
     *
     * @return the new <code>VInteger</code>
     *
     * @throws IllegalArgumentException if the <code>encodedValue</code> can not be decoded as a variable size integer
     */
    public static VInteger decode(long encodedValue) {
        int encodedSize = 1;
        while (encodedSize <= 8
                && (encodedValue & VALUE_MASK[encodedSize - 1]) != (encodedValue ^ LENGTH_DESCRIPTOR[encodedSize - 1])) {
            encodedSize++;
        }
        if (encodedSize > 8) {
            throw new IllegalArgumentException();
        }
        return new VInteger(encodedValue & VALUE_MASK[encodedSize - 1], encodedValue, encodedSize);
    }

    /**
     * Creates a new <code>VInteger</code> with the specified value.
     *
     * @param encodedValue the value in the encoded form
     * @param encodedSize the size of the value in the encoded form
     *
     * @return the new <code>VInteger</code>
     *
     * @throws IllegalArgumentException if <code>encodedSize</code> is less then <code>1</code> or greater then
     * <code>8</code>, or if the <code>encodedValue</code> can not be decoded as a variable size integer of the
     * specified size
     */
    public static VInteger decode(long encodedValue, int encodedSize) {
        if (encodedSize < 1 || encodedSize > 8
                || (encodedValue & VALUE_MASK[encodedSize - 1]) != (encodedValue ^ LENGTH_DESCRIPTOR[encodedSize - 1])) {
            throw new IllegalArgumentException();
        }
        return new VInteger(encodedValue & VALUE_MASK[encodedSize - 1], encodedValue, encodedSize);
    }

    /**
     * Creates new <code>VInteger</code> with the reserved value.
     *
     * @param encodedSize the size of the value in the encoded form
     *
     * @return the new <code>VInteger</code>
     *
     * @throws IllegalArgumentException if <code>encodedSize</code> is less then <code>1</code> or greater then
     * <code>8</code>
     */
    public static VInteger createReserved(int encodedSize) {
        if (encodedSize < 1 || encodedSize > 8) {
            throw new IllegalArgumentException();
        }
        return new VInteger(VALUE_MASK[encodedSize - 1], LENGTH_DESCRIPTOR[encodedSize - 1] | VALUE_MASK[encodedSize - 1], encodedSize);
    }


    /**
     * Returns the value.
     *
     * @return the value
     */
    public long getValue() {
        return value;
    }

    /**
     * Returns the value in the encoded form.
     *
     * @return the encoded value
     */
    public long getEncodedValue() {
        return encodedValue;
    }

    /**
     * Returns the size of the value in the encoded form.
     *
     * @return the encoded value size
     */
    public int getEncodedSize() {
        return encodedSize;
    }

    /**
     * Returns <code>true</code> if this <code>VInteger</code> value is reserved, <code>false</code> otherwise.
     *
     * @return <code>true</code> if the encoded value of this object is reserved; <code>false</code> otherwise
     */
    public boolean isReserved() {
        return (value & VALUE_MASK[encodedSize - 1]) == VALUE_MASK[encodedSize - 1];
    }

    /**
     * Returns <code>true</code> if this <code>VInteger</code> value can represent a value element identifier;
     * <code>false</code> otherwise.
     *
     * @return <code>true</code> if the encoded value of this object is valid identifier; <code>false</code> otherwise
     */
    public boolean isIdentifier() {
        return encodedSize == 1
                || (value & VALUE_MASK[encodedSize - 2]) != value
                || VALUE_MASK[encodedSize - 2] == value;
    }


    @Override
    public int hashCode() {
        int result = 17;
        result = 37 * result + (int) (value ^ value >>> 32);
        result = 37 * result + (int) (encodedValue ^ encodedValue >>> 32);
        result = 37 * result + encodedSize;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (obj instanceof VInteger) {
            VInteger v = (VInteger) obj;
            return value == v.value
                    && encodedValue == v.encodedValue
                    && encodedSize == v.encodedSize;
        } else {
            return false;
        }
    }

    @Override
    public String toString() {
        StringBuilder buffer = new StringBuilder();
        buffer.append("VInteger(")
                .append("value=").append(value)
                .append(',').append("encodedValue=0x").append(Long.toHexString(encodedValue))
                .append(',').append("encodedSize=").append(encodedSize)
                .append(')');
        return buffer.toString();
    }

}
